package com.tuling.core;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.tuling.core.loader.MyClassLoader;

/**
 * Spring上下文工具类
 *
 */
@SuppressWarnings("unchecked")
@Component("SpringContextUtil")
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringContextUtil.context = context;
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return context.getBean(name, requiredType);
    }

    public static <T> T getBean(String name, Object... args) {
        return (T) context.getBean(name, args);
    }

    public static <T> T getBean(Class<T> requiredType) { return context.getBean(requiredType); }

	public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    public static boolean containsBean(String name) {
        return context.containsBean(name);
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }
    
    /**
     * 从自定义classloader加载class到spring容器
     * @param beanId
     * @param fullClassName
     * @param myLoader
     */
    public static <T> void dynamicAddPlugin(String beanId,String fullClassName,MyClassLoader myLoader){
    	BeanDefinition bean = new GenericBeanDefinition();
    	//加载类的全路径
        bean.setBeanClassName(fullClassName);
        DefaultListableBeanFactory fty = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();
        //注册Bean
        fty.registerBeanDefinition(beanId, bean);
        fty.setBeanClassLoader(myLoader);
        context.getBean(beanId);
    }
    
    /**
     * 动态删除一个bean
     */
    public static void dynamicRemovePlugin(String beanId){
    	DefaultListableBeanFactory acf = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();
    	if(acf.containsBean(beanId)) {
    		/*MyPlugin plugin = (MyPlugin) context.getBean(beanId);
    	    plugin.destory();*/
    	    acf.removeBeanDefinition(beanId);
    	}
    }
}